<template>
  <Toast/>
  <!-- 关闭编辑器内容提示 -->
  <ConfirmDialog/>
  <!-- 私聊聊天室 -->
  <PrivateChatDialog :show="chatDialogShow"
                     @hide="chatDialogShow = false"/>
  <div class="h-screen-calc w-screen-calc">
    <router-view v-if="routerAlive"/>
  </div>
</template>

<script setup lang="ts">
/** JS */
import {nextTick, ref, provide, inject, onMounted} from 'vue';
import {Websocket, WebsocketConfig} from '@/utils/Webscoket';
import Cache from '@/utils/Cache';
/** 组件 */
import Toast from 'primevue/toast';
import ConfirmDialog from 'primevue/confirmdialog';
import {UserMsg} from "@/interface/user/entity/UserEntityInterface";
import {MessageTypes} from "@/interface/websocket/entity/SocketMessage";
import PrivateChatDialog from '@/components/dialog/PrivateChatDialog.vue';

/** 私聊聊天室 */
let chatDialogShow = ref(false);
const showChatDialog = () => {
  chatDialogShow.value = true;
}
const privateChatDialogHideHandler = (val) => {
  chatDialogShow.value = val;
}
provide('showChatDialog', showChatDialog);

/**
 * 刷新页面
 */
let routerAlive = ref(true);
const reload = () => {
      routerAlive.value = false;
      nextTick(() => routerAlive.value = true);
    },
    cache = new Cache(),
    userMsg: UserMsg = cache.get('userMsg');
provide('reload', reload);

/** Websocket 连接 */
// 全局注入 websocket 并启动
const isHttps = 'https:' == document.location.protocol;
let socketUrl = 'ws://yeziji.xyz/chat/';
if (isHttps) {
  // alert("这是一个https请求");
  socketUrl = 'wss://yeziji.xyz/chat/'
}

const messages: Array<(event) => void> = [];
const websocketConfig: WebsocketConfig = {
  url: `${process.env.NODE_ENV === 'production' ? socketUrl : 'ws://127.0.0.1:12345/chat'}`,
  heartTime: 30000,
  reconnectTime: 5000,
  waitSend: 1500,
  onMessage: (event) => {
    // 遍历 messages 集合并触发
    messages.forEach(f => {
      f.call(null, event);
    });
  }
}
const websocket = new Websocket(websocketConfig);
websocket.create();

if (userMsg !== null) {
  // 如果 userMsg 存在则自动发送登录请求
  websocket.send({
    type: MessageTypes.UserLogin,
    context: userMsg
  })
}
provide('messages', messages);
provide('websocket', websocket);
</script>

<style lang="less">
@import './assets/common.less';
/** 登录注册框响应式高度 */
.login-content {
  height: 320px !important;
  overflow: hidden !important;
}

.register-content {
  @media screen and (min-width: 992px) {
    height: 600px !important;
  }
  @media screen and (min-width: 576px) and (max-width: 992px) {
    height: 600px !important;
  }
  @media screen and (min-width: 320px) and (max-width: 576px) {
    height: 576px !important;
  }
  overflow: hidden !important;
}
</style>

